import 'dart:io';

import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mtf/app/base/BaseController.dart';
import 'package:mtf/app/net/HttpManger.dart';
import 'package:mtf/app/routes/app_pages.dart';
import 'package:mtf/app/utils/cache/AppCahche.dart';
import 'package:path_provider/path_provider.dart' as path_provider;

/**
 * GetX Template Generator - fb.com/htngu.99
 * */

class mineInfoController extends BaseController {
  var user = AppCache.getUserInfo().obs;
  final _picker = ImagePicker();

  void clickEditName() async{
    await Get.toNamed(Routes.EDIT_NICK_NAME);
    reqUserInfo();
  }

  void clickEditEmail() async{
   await Get.toNamed(Routes.EDIT_EMAIL);
   reqUserInfo();
  }

  void clickUpdateImage() async {
    final pickedFile = await _picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      // 处理所选照片
      reqFileUpload(File(pickedFile.path));
    }
  }

  void reqFileUpload(File file) async {
    print('reqFileUpload${file.path}');
    showLoading();
    var newFile = await compressAndGetFile(file);
    print('newFile${newFile.path}');
    var fileResp = await HttpManager.reqFileUpLoad(newFile);
    if (fileResp.isSuccess() && fileResp.data != null) {
      var resp=await HttpManager.reqUpdateInfo(head_url: fileResp.data!.fileNameUrl);
      reqUserInfo();
      SmartDialog.showNotify(msg: "修改成功", notifyType: NotifyType.success);
    }
    hideLoading();
  }



  /// 图片压缩 File -> File
  Future<File> compressAndGetFile(File file) async {
    final dir = await path_provider.getTemporaryDirectory();
    await dir.create(recursive: true);
    final targetPath =
        dir.absolute.path + '/${DateTime.now().microsecondsSinceEpoch}.jpg';
    var result = await FlutterImageCompress.compressAndGetFile(
      file.path,
      targetPath,
      quality: 88,
      rotate: 0,
    );
    return File(result!.path);
  }

  void reqUserInfo() async {
    var resp=await HttpManager.reqUserInfo();
    if(resp.isSuccess()&&resp.data!=null){
      AppCache.setUserInfo(resp.data!);
      user.value = resp.data!;
    }
  }

  @override
  void onReady() {
    super.onReady();
    reqUserInfo();
  }
}
